

import javax.comm.CommPortIdentifier;
import javax.comm.SerialPort;
import javax.comm.PortInUseException;
import javax.comm.UnsupportedCommOperationException;
import java.io.IOException;
import com.ridgesoft.io.Mailbox;

public class RobotComm{

    protected String id;
    protected Robot robot;
    private SerialPort port;
    private Mailbox mailbox;
    
    public RobotComm(String id, CommPortIdentifier cpi)throws PortInUseException, UnsupportedCommOperationException, IOException {
        this.id = id;
        port = (SerialPort) cpi.open(id, 1000);
        port.setSerialPortParams(115200, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
        mailbox = new Mailbox(port.getInputStream(), port.getOutputStream(), 6, 1);
        mailbox.open(5000);
    }

    public void send(byte[] data){
        try{
            mailbox.postMessage(data);
        }catch(IOException ex){
            ex.printStackTrace();
        }
    }

    public void send(byte data){
        try{
            mailbox.postMessage(new byte[]{data});
        }catch(IOException ex){}
    }

    public byte[] receive(){
        try{
            return mailbox.getMessage();
        }catch(IOException ex){
            return null;
        }
    }

    public void close(){
        mailbox.close();
        port.close();
    }


}
